#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
样式管理器模块
负责加载和应用QSS样式
"""

import os
import logging
from pathlib import Path
from typing import Optional

from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QDir, QSettings, QObject, Signal
from PySide6.QtGui import QIcon, QPalette

logger = logging.getLogger("style_manager")


class StyleManager(QObject):
    """样式管理器类"""
    
    # 添加主题切换信号
    theme_changed = Signal(str)
    
    def __init__(self):
        """初始化样式管理器"""
        super().__init__()
        self.current_theme = "modern_light"
        self.styles_dir = Path(__file__).parent / "resources" / "styles"
        self.icons_dir = Path(__file__).parent / "resources" / "icons"
        self.settings = QSettings()
        
        # 加载保存的主题设置
        self._load_theme_settings()
        
    def _load_theme_settings(self):
        """加载保存的主题设置"""
        saved_theme = self.settings.value("theme", "auto")
        if saved_theme == "auto":
            # 自动检测系统主题
            self.current_theme = self._detect_system_theme()
        else:
            self.current_theme = saved_theme
            
    def _detect_system_theme(self) -> str:
        """检测系统主题
        
        Returns:
            主题名称
        """
        try:
            app = QApplication.instance()
            if app:
                palette = app.palette()
                # 检查窗口背景色的亮度来判断是否为深色主题
                window_color = palette.color(QPalette.Window)
                # 计算亮度（使用标准公式）
                brightness = (window_color.red() * 0.299 + 
                            window_color.green() * 0.587 + 
                            window_color.blue() * 0.114)
                
                # 如果亮度小于128，认为是深色主题
                if brightness < 128:
                    return "modern_dark"
                else:
                    return "modern_light"
        except Exception as e:
            logger.warning(f"检测系统主题失败，使用默认浅色主题: {e}")
            
        return "modern_light"
    
    def load_theme(self, theme_name: str = None) -> bool:
        """加载指定主题
        
        Args:
            theme_name: 主题名称，如果为None则使用当前主题
            
        Returns:
            是否加载成功
        """
        if theme_name is None:
            theme_name = self.current_theme
            
        try:
            theme_file = self.styles_dir / f"{theme_name}.qss"
            
            if not theme_file.exists():
                logger.error(f"主题文件不存在: {theme_file}")
                return False
            
            # 读取QSS文件
            with open(theme_file, 'r', encoding='utf-8') as f:
                qss_content = f.read()
            
            # 替换图标路径为绝对路径
            qss_content = self._resolve_icon_paths(qss_content)
            
            # 应用样式
            app = QApplication.instance()
            if app:
                app.setStyleSheet(qss_content)
                old_theme = self.current_theme
                self.current_theme = theme_name
                
                # 保存主题设置
                self.settings.setValue("theme", theme_name)
                self.settings.sync()
                
                # 发出主题切换信号
                if old_theme != theme_name:
                    self.theme_changed.emit(theme_name)
                
                logger.info(f"成功加载主题: {theme_name}")
                return True
            else:
                logger.error("无法获取QApplication实例")
                return False
                
        except Exception as e:
            logger.error(f"加载主题失败: {str(e)}")
            return False
    
    def set_theme(self, theme_name: str) -> bool:
        """设置主题
        
        Args:
            theme_name: 主题名称 ("modern_light", "modern_dark", 或 "auto")
            
        Returns:
            是否设置成功
        """
        if theme_name == "auto":
            # 自动主题：检测系统主题
            detected_theme = self._detect_system_theme()
            success = self.load_theme(detected_theme)
            if success:
                # 保存用户选择为自动
                self.settings.setValue("theme", "auto")
                self.settings.sync()
            return success
        else:
            # 指定主题
            return self.load_theme(theme_name)
    
    def get_current_theme(self) -> str:
        """获取当前主题名称
        
        Returns:
            当前主题名称
        """
        return self.current_theme
    
    def get_theme_setting(self) -> str:
        """获取用户的主题设置
        
        Returns:
            主题设置 ("modern_light", "modern_dark", 或 "auto")
        """
        return self.settings.value("theme", "auto")
    
    def is_dark_theme(self) -> bool:
        """判断当前是否为深色主题
        
        Returns:
            是否为深色主题
        """
        return self.current_theme == "modern_dark"
    
    def _resolve_icon_paths(self, qss_content: str) -> str:
        """解析QSS中的图标路径为绝对路径
        
        Args:
            qss_content: QSS内容
            
        Returns:
            处理后的QSS内容
        """
        # 将相对路径替换为绝对路径
        icons_path = str(self.icons_dir).replace('\\', '/')
        qss_content = qss_content.replace('url(icons/', f'url({icons_path}/')
        
        return qss_content
    
    def get_icon(self, icon_name: str) -> QIcon:
        """获取图标
        
        Args:
            icon_name: 图标名称（不含扩展名）
            
        Returns:
            QIcon对象
        """
        icon_path = self.icons_dir / f"{icon_name}.svg"
        
        if icon_path.exists():
            return QIcon(str(icon_path))
        else:
            logger.warning(f"图标文件不存在: {icon_path}")
            return QIcon()
    
    def apply_compact_mode(self, enable: bool = True):
        """应用紧凑模式
        
        Args:
            enable: 是否启用紧凑模式
        """
        app = QApplication.instance()
        if not app:
            return
        
        current_style = app.styleSheet()
        
        if enable:
            # 添加紧凑模式样式
            compact_style = """
            /* 紧凑模式额外样式 */
            QDockWidget::title {
                padding: 4px 8px;
                font-size: 12px;
            }
            
            QTabBar::tab {
                padding: 4px 12px;
                font-size: 12px;
            }
            
            QPushButton {
                padding: 4px 12px;
                font-size: 12px;
            }
            
            QToolButton {
                padding: 4px;
                min-width: 20px;
                min-height: 20px;
            }
            
            QMenuBar::item {
                padding: 4px 8px;
                font-size: 12px;
            }
            
            QMenu::item {
                padding: 6px 12px;
                font-size: 12px;
            }
            
            QHeaderView::section {
                padding: 6px 8px;
                font-size: 11px;
            }
            
            QListView::item, QTreeView::item {
                padding: 3px 6px;
            }
            
            QTableView::item {
                padding: 4px 6px;
            }
            """
            app.setStyleSheet(current_style + compact_style)
        else:
            # 重新加载原始主题
            self.load_theme(self.current_theme)
    
    def set_icon_theme(self, widget, icon_mappings: dict):
        """为组件设置图标主题
        
        Args:
            widget: 要设置图标的组件
            icon_mappings: 图标映射字典 {action_name: icon_name}
        """
        for action_name, icon_name in icon_mappings.items():
            if hasattr(widget, action_name):
                action = getattr(widget, action_name)
                if hasattr(action, 'setIcon'):
                    action.setIcon(self.get_icon(icon_name))
    
    def get_available_themes(self) -> list:
        """获取可用主题列表
        
        Returns:
            主题名称列表
        """
        themes = []
        if self.styles_dir.exists():
            for file in self.styles_dir.glob("*.qss"):
                themes.append(file.stem)
        return themes
    
    def refresh_theme(self):
        """刷新当前主题（重新检测系统主题）"""
        current_setting = self.get_theme_setting()
        if current_setting == "auto":
            # 如果是自动主题，重新检测系统主题
            new_theme = self._detect_system_theme()
            if new_theme != self.current_theme:
                self.load_theme(new_theme)
        else:
            # 如果是手动设置的主题，重新加载
            self.load_theme(current_setting)


# 全局样式管理器实例
_style_manager = None

def get_style_manager() -> StyleManager:
    """获取样式管理器单例
    
    Returns:
        StyleManager实例
    """
    global _style_manager
    if _style_manager is None:
        _style_manager = StyleManager()
    return _style_manager

def apply_modern_theme():
    """应用现代化主题"""
    style_manager = get_style_manager()
    return style_manager.load_theme()

def apply_compact_mode(enable: bool = True):
    """应用紧凑模式"""
    style_manager = get_style_manager()
    style_manager.apply_compact_mode(enable)

def get_icon(icon_name: str) -> QIcon:
    """获取图标"""
    style_manager = get_style_manager()
    return style_manager.get_icon(icon_name)

def set_theme(theme_name: str) -> bool:
    """设置主题"""
    style_manager = get_style_manager()
    return style_manager.set_theme(theme_name)
